#include "mainwindow.h"
#include "dialog.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QTime>
#include <QDateTime>
#include <QFile>
#include <QMessageBox>
#include <QSettings>
#include <QFileDialog>

#define SETTING_ISRUNNING   "isrunning"
#define SETTING_GEOMETRY    "geometry"

#define BLOG_HOST   "www.wretch.cc"      // Host
#define BLOG_URL    "/blog/joejoejoe"    // Joejoejoe's page

#define INVERTAL    300*1000             // 300 seconds

#define STR_PATTEN  "<spanclass=\"description\">" // Pattern for determining

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QSettings s;
    int bIsRunning = s.value(SETTING_ISRUNNING, 0).toInt(); // Check is running, default is not
    if(bIsRunning>0){
        int yesno = QMessageBox::warning(this,tr("Is running?"),tr("Hey, i think you're running duplicated apps at the same time, are you still sure to run one more app?"), tr("Yes, i do."), tr("No, thanks"));
        if(yesno==1)
            exit(0);
    }
    s.setValue(SETTING_ISRUNNING, 1);

    // Load geometry from setting
    this->restoreGeometry(s.value(SETTING_GEOMETRY,this->saveGeometry()).toByteArray());

    // Http instance
    http = new QHttp(this);

    // Connect http object
    connect(http,SIGNAL(requestFinished(int,bool)),this,SLOT(requestFinished(int,bool)));
    connect(http,SIGNAL(readyRead(QHttpResponseHeader)),this,SLOT(readyRead(QHttpResponseHeader)));
    connect(http,SIGNAL(done(bool)),this,SLOT(done(bool)));

    // Connect timer
    connect(&timer,SIGNAL(timeout()),this,SLOT(timeout()));

    http->setHost(BLOG_HOST);
    this->displayDataToUi();
    this->timeout();
    timer.start(INVERTAL);

    // Create tray icon and actions
    createTrayActions();
    createTrayIcon();
    setTrayIcon();
    trayIcon->show();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::displayDataToUi()
{
    // Display file on UI
    QFile reader("./joejoejoe.txt"); reader.open(QFile::ReadOnly|QFile::Text);
    QTextStream in(&reader);
    QString buffText = in.readAll();
    QStringList buffStack = buffText.split('\n');
    buffText = QString();
    for(int i=buffStack.size()-1; i>=0; i--){
        if(buffStack.at(i)=="")continue;
        buffText += buffStack.at(i) + "<br />";
    }
    ui->textBrowser->document()->setHtml(buffText);
}

void MainWindow::requestFinished(int id, bool error)
{
    if(requesID==id)
    {
        QString s = strBuffer;
        while(http->bytesAvailable()>0)
        {
            QString _temp =
            s+=_temp;
        }
        s.remove(QRegExp("[\\s|\\n|\\r]"));

        int index = 0;
        while(1)
        {
             int i1 = s.indexOf(STR_PATTEN,index);
             if(i1<0) // Not found
                 break;

             int i2 = s.indexOf("</span>",i1);

             // Substring
             QString subStr = s.mid(i1,i2-i1);
             subStr.remove(STR_PATTEN);


             if(subStr=="") goto loop_end;
             if(strData==subStr) // no change
                 ;
             else{
                 // TODO: Do something
                 QFile file("./joejoejoe.txt");                 
                 file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
                 QTextStream out(&file);
                 out << QDateTime::currentDateTime().toString() << ": ";
                 out << subStr;
                 out << "\r\n";
                 file.close();

                 this->displayDataToUi();
             }
             strData = subStr; //update
    loop_end:
             index = i2;
        }
    }
}

void MainWindow::readyRead(const QHttpResponseHeader &resp)
{
    strBuffer += QUrl::fromPercentEncoding(http->readAll().toPercentEncoding());
    return;
}

void MainWindow::done(bool error)
{
    strBuffer = ""; // Clear buffer
    ui->statusBar->showMessage(QString("Last updated: %1").arg(QDateTime::currentDateTime().toString()));
}

void MainWindow::timeout()
{
    // Don't care the HTTP state, just read again lol!
    requesID = http->get(BLOG_URL);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    int yesno = QMessageBox::question(this,tr("Exit"), tr("Do you want to hide to tray rather than exit?"), tr("Yes, hide it!"), tr("No, take me away."));
    if(yesno==0){
        this->showHideTray->trigger();
        event->ignore();
        return;
    }else{
        QSettings s;
        s.setValue(SETTING_GEOMETRY, this->saveGeometry());
        s.setValue(SETTING_ISRUNNING, 0);
    }
    QWidget::closeEvent(event);
}

void MainWindow::on_action_Save_as_triggered()
{
    QString filename = QFileDialog::getSaveFileName(
                this,
                tr("Save As..."),
                QDir::currentPath(),
                tr("Text (*.txt)") );
    if( !filename.isNull() )
    {
        QFile file(filename);
        file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
        QTextStream out(&file);
        out << ui->textBrowser->document()->toPlainText();
        file.close();
    }
}

void MainWindow::changeEvent(QEvent *event)
{
    QMainWindow::changeEvent(event);
    if(event->type() == QEvent::WindowStateChange) {
        if(isMinimized()){
           //this->setWindowState(Qt::WindowMaximized);
           //this->hide();
        }
    }

    QWidget::changeEvent(event);
}

void MainWindow::showHideWindow()
{
    if(this->isVisible())
    {
        this->hide();
        showHideTray->setIcon(QIcon(":/images/arrow_up.ico"));
        showHideTray->setText("Show Main Window");
    }
    else
    {
        this->show();
        showHideTray->setIcon(QIcon(":/images/arrow_down.ico"));
        showHideTray->setText("Hide Main Window");
    }
}

void MainWindow::trayIconClicked(QSystemTrayIcon::ActivationReason reason)
{
    if(reason == QSystemTrayIcon::DoubleClick)
        showHideWindow();
}

void MainWindow::setTrayIcon()
{
    trayIcon->setIcon(QIcon(":/rss-icon.png"));
}

void MainWindow::createTrayIcon()
{
    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(showHideTray);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(closeTray);

    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);

    connect(
            trayIcon,
          SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this,
            SLOT(trayIconClicked(QSystemTrayIcon::ActivationReason))
           );
}
void MainWindow::createTrayActions()
{
    showHideTray = new QAction(tr("&Hide Main Window"), this);
    connect(showHideTray, SIGNAL(triggered()), this, SLOT(showHideWindow()));
    showHideTray->setIcon(QIcon(":/images/arrow_down.ico"));
    closeTray = new QAction(tr("&Exit"), this);
    connect(closeTray, SIGNAL(triggered()), this, SLOT(close()));
    closeTray->setIcon(QIcon(":/images/Delete.png"));
}

void MainWindow::on_action_JoejoejoeReader_triggered()
{
    Dialog dlg;
    dlg.exec();
}

void MainWindow::on_actionHide_to_Tray_triggered()
{
    this->showHideTray->trigger();
}

void MainWindow::on_action_Exit_triggered()
{
    this->close();
}
